package com.rocketmq.base.example.tran;

import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;

import java.time.LocalDateTime;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

public class TransactionListenerImpl implements TransactionListener {
    private AtomicInteger transactionIndex = new AtomicInteger(0);

    private ConcurrentHashMap<String, Integer> localTrans = new ConcurrentHashMap<>();
    //执行本地事物
    @Override
    public LocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        System.out.println("执行本地事物" + msg.getTags() + LocalDateTime.now());
//        int value = transactionIndex.getAndIncrement();
//        int status = value % 3;
//        localTrans.put(msg.getTransactionId(), status);
//        return LocalTransactionState.UNKNOW;
        if ("TagA".equals(msg.getTags())){
            return LocalTransactionState.COMMIT_MESSAGE;
        }else if ("TagB".equals(msg.getTags())){
            return LocalTransactionState.ROLLBACK_MESSAGE;
        }else {
            return LocalTransactionState.UNKNOW;
        }
    }

    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt msg) {
        System.out.println("检查本地事物" + msg.getTags() + LocalDateTime.now());
//        Integer status = localTrans.get(msg.getTransactionId());
//        if (null != status) {
//            switch (status) {
//                case 0:
//                    return LocalTransactionState.UNKNOW;
//                case 1:
//                    return LocalTransactionState.COMMIT_MESSAGE;
//                case 2:
//                    return LocalTransactionState.ROLLBACK_MESSAGE;
//            }
//        }
        String tags = msg.getTags();
        if ("TagB".equals(tags) || "TagA".equals(tags)){
            System.err.println("这两种情况不会发生");
        }
        if ("TagC".equals(tags)){
            return LocalTransactionState.COMMIT_MESSAGE;
        }else if ("TagD".equals(tags)){
            return LocalTransactionState.ROLLBACK_MESSAGE;
        }
        if ("TagE".equals(tags)){
            System.out.println("第几次TagE来了:"+transactionIndex.incrementAndGet());
        }
        //"TagE...."
        return LocalTransactionState.UNKNOW;
    }

    public static void main(String[] args) {
        int andIncrement = new AtomicInteger(0).getAndIncrement();
        System.out.println(andIncrement);
    }
}
